<template>
	<div>
		<el-form :inline="true" class="search-form" :model="searchData">
			<el-form-item label="用户名称">
				<el-input
					v-model="searchData.nickName"
					placeholder="请输入用户名称"
					clearable
				></el-input>
			</el-form-item>

			<el-form-item label="用户角色">
				<el-select
					v-model="searchData.roleId"
					class="role-select"
					size="large"
					placeholder="请选择角色"
					clearable
					value-key="roleId"
				>
					<el-option label="全部" :value="0" />
					<el-option
						v-for="item in roleList"
						:key="item.roleId"
						:label="item.roleName"
						:value="item.roleId"
					/>
				</el-select>
			</el-form-item>

			<el-form-item>
				<!-- <el-button
					type="primary"
					size="default"
					>查询</el-button
				> -->
				<el-button @click="resetSearch" size="default">重置</el-button>
			</el-form-item>
		</el-form>
		<el-table :data="filteredUserList" border style="width: 100%">
			<el-table-column prop="id" label="编号" width="180" />
			<el-table-column prop="nickName" label="用户昵称" width="180" />
			<el-table-column prop="role" label="用户角色">
				<template #default="scope">
					<el-button
						v-for="item in scope.row.role"
						:key="item.roleId"
						type="primary"
						size="default"
						color="#000"
					>
						{{ item.roleName }}
					</el-button>
				</template>
			</el-table-column>
			<el-table-column prop="role" label="操作">
				<template #default="scope">
					<el-button
						type="primary"
						size="default"
						@click="handleEditUser(scope.row)"
						color="#000"
						v-auth="'user:edit'"
					>
						编辑
					</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-dialog v-model="editShow" title="编辑用户信息">
			<el-form :model="editUser">
				<el-form-item label="用户昵称" label-width="120px">
					<el-input
						v-model="editUser.nickName"
						class="w192"
						autocomplete="off"
					/>
				</el-form-item>

				<el-form-item label="用户角色" label-width="120px">
					<el-select
						v-model="editUser.roleIds"
						multiple
						class="m-2"
						size="large"
						placeholder="请选择角色"
					>
						<el-option
							v-for="item in roleList"
							:key="item.roleId"
							:label="item.roleName"
							:value="item.roleId"
						/>
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="editShow = false">取消</el-button>
					<el-button type="primary" @click="ensureEditUser"
						>修改</el-button
					>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { getUserList } from "@/api/user";
import { getRoleList } from "@/api/role";
import {
	IUser,
	IRole, // 使用统一的 IRole
	IQueryUser,
	IUserEdit,
} from "@/types/common.js";

// 用户列表（原始数据）
const originalUserList = ref<IUser[]>([]);
// 角色列表 (不再需要 IRoleWithAuth)
const roleList = ref<IRole[]>([]);
// 用于高效查找角色的 Map (ID -> 角色对象)
const roleMap = new Map<number, IRole>();

const filteredUserList = computed(() => {
	// 始终从原始的完整列表开始过滤
	let result = originalUserList.value;
	// 如果没有原始数据，直接返回空数组
	const nameQuery = searchData.nickName.trim().toLowerCase();
	// 如果存在昵称查询，则按昵称过滤
	if (nameQuery) {
		result = result.filter(item =>
			item.nickName.toLowerCase().includes(nameQuery)
		);
	}
	// 如果选择了某个角色 (而不是“全部”)，则按角色过滤
	if (searchData.roleId) {
		result = result.filter(item =>
			item.role.some(r => r.roleId === searchData.roleId)
		);
	}
	return result;
});

// 查询数据
const searchData = reactive<IQueryUser>({
	nickName: "",
	roleId: 0, // 0 代表“全部”
});

// 重置搜索
const resetSearch = () => {
	searchData.nickName = "";
	searchData.roleId = 0;
	// filteredUserList.value = [...originalUserList.value];
};

// 编辑用户弹窗
const editShow = ref(false);

// 编辑用户信息
const editUser = reactive<IUserEdit>({
	id: 0,
	nickName: "",
	userName: "",
	roleIds: [], // <--- 使用 roleIds
});

// 编辑用户: 使用显式赋值，避免 Object.assign 的歧义
const handleEditUser = (row: IUser) => {
	editUser.id = row.id;
	editUser.nickName = row.nickName;
	editUser.userName = row.userName;
	// 将用户的角色对象数组映射为 ID 数组
	editUser.roleIds = row.role.map(r => r.roleId);
	editShow.value = true;
};

//  确认编辑用户
const ensureEditUser = () => {
	const userToUpdate = originalUserList.value.find(
		item => item.id === editUser.id
	);
	if (!userToUpdate) {
		console.error("编辑时未找到用户!");
		editShow.value = false;
		return;
	}
	userToUpdate.nickName = editUser.nickName;
	// 使用 roleIds 将 ID 数组映射回完整的角色对象数组
	userToUpdate.role = editUser.roleIds
		.map(id => roleMap.get(id)) // 从 Map 中查找角色对象
		.filter((role): role is IRole => !!role); // 过滤掉未找到的并进行类型收窄

	editShow.value = false;
};

// --- 数据获取 ---
const fetchInitialData = async () => {
	try {
		// 使用 Promise.all 并行获取用户和角色，提升性能
		const [userRes, roleRes] = await Promise.all([
			getUserList(),
			getRoleList(),
		]);

		originalUserList.value = userRes;
		roleList.value = roleRes;

		// 清空并重建 Map
		roleMap.clear();
		roleRes.forEach((role: IRole) => roleMap.set(role.roleId, role));
	} catch (error) {
		console.error("初始化数据获取失败:", error);
	}
};

// 初始化
onMounted(() => {
	fetchInitialData();
});
</script>

<style scoped lang="less">
.search-form {
	padding: 10px 0 0 10px;
}

.w192 {
	width: 192px;
}

.role-select {
	width: 200px;
}
</style>
